package com.easy.secret.codec;

import java.io.UnsupportedEncodingException;
import java.util.Objects;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

/**
 * @ProjectName: esay-secret-server
 * @Package: com.easy.secret.codec
 * @ClassName: Base64Codec
 * @Description: BASE64解码器-单例模式
 * @Author: wangjc
 * @CreateDate: 2023/11/17
 * @UpdateUser: wangjc
 * @UpdateDate: 2023/11/17
 * @UpdateRemark: 更新内容
 * @Version: 1.0
 */
public class Base64Codec {
    private Base64 base64 = new Base64();
    private static Base64Codec base64Codec;

    private Base64Codec() {
    }

    public static Base64Codec instance() {
        if (Objects.isNull(base64Codec)) {
        	synchronized(Base64Codec.class) {
        		if (Objects.isNull(base64Codec)) {
        			base64Codec = new Base64Codec();
        		}
			}
        }

        return base64Codec;
    }

    public String encode(String original) throws UnsupportedEncodingException {
        return this.encode(original, (String)null);
    }

    public String encode(String original, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(original)) {
            return null;
        } else {
            if (StringUtils.isBlank(charset)) {
                charset = "UTF-8";
            }

            return this.base64.encodeToString(original.getBytes(charset));
        }
    }

    public String encode(byte[] original) throws UnsupportedEncodingException {
        return this.base64.encodeToString(original);
    }

    public String decode(String base64) throws UnsupportedEncodingException {
        return this.decode(base64, (String)null);
    }

    public String decode(String base64, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(base64)) {
            return null;
        } else {
            if (StringUtils.isBlank(charset)) {
                charset = "UTF-8";
            }

            byte[] decode = this.base64.decode(base64.getBytes(charset));
            return new String(decode, charset);
        }
    }

    public byte[] decodeByte(String base64, String charset) throws UnsupportedEncodingException {
        if (StringUtils.isBlank(base64)) {
            return null;
        } else {
            if (StringUtils.isBlank(charset)) {
                charset = "UTF-8";
            }

            return this.base64.decode(base64.getBytes(charset));
        }
    }
}
